#include "clientHead.h"
/* Usage:./client 127.0.0.1 12345 */
typedef struct {
    int length;
    char data[1000];
}train_t;

int main(int argc, char *argv[]){
    ARGS_CHECK(argc, 3);
    // 获取用户名
    char username[1000] = {0};
    printf("请输入用户名: ");
    fgets(username, sizeof(username), stdin);
    // 去除最后一个换行符
    if(username[strlen(username)-1] == '\n'){
        username[strlen(username)-1] = 0;
    }

    // 改变权限  先升级为root， 以执行验证密码， 再降为自己
    uid_t uid = getuid();
    if(setuid(0) == -1) {
        printf("权限不够\n");
        return 0;
    }

    // 登陆检查
    while(1){
        if(login_check(username) == true){
            break;
        } 
    }
    
    if(setuid(uid) == -1) {
        printf("权限不够\n");
        return 0;
    }

    // TCP
    int sockfd = tcpInit(argv[1], argv[2]);
    printf("Connect is success! sockfd = %d\n\n", sockfd);
    // 小火车发送用户名
    train_t train;
    train.length = strlen(username);
    memcpy(train.data, username, train.length);
    send(sockfd, &train, sizeof(train.length)+train.length, MSG_NOSIGNAL);  
    while(1){
        dealCommand(sockfd, username);
    }
    close(sockfd);
    return 0;
}
